import React, { useEffect, useRef, useState } from "react";
// 高阶组件：本质上就是一个函数， 函数的参数接受是一个组件， 返回值也是一个组件。
// 高阶组件：本身并不是 react 的什么语法， 而是根据react特性，组件复用的高级技巧
// 高阶组件
const withDrag = (Comp) => {
  return () => {
    const div = useRef();
    let flag = false
    // 按下
    const onMouseDown = (e) => {
      div.current.style.position = "fixed";
      div.current.style.left = e.pageX + "px";
      div.current.style.top = e.pageY + "px";
      flag = true
    };
    // 移动
    const mousemove = (e) => {
      if (flag) {
        div.current.style.left = e.pageX + "px";
        div.current.style.top = e.pageY + "px";
      }
    };
    // 抬起
    const mouseup = () => {
      flag = false
    };

    useEffect(() => {
      document.addEventListener("mousemove", mousemove);
      document.addEventListener("mouseup", mouseup);
    }, []);

    return (
      <div ref={div} onMouseDown={(e) => onMouseDown(e)}>
        <Comp></Comp>
      </div>
    );
  };
};



const Button1 = () => <button>1</button>;
const Button2 = () => <button>2</button>;
const Button3 = () => <button>3</button>;
const Button4 = () => <button>4</button>;
const Images = () => <img draggable="false" src="https://robohash.org/1231231" alt="" style={{ border: '1px solid #ccc' }}></img>;

const Button1Drag = withDrag(Button1);
const Button2Drag = withDrag(Button2);
const Button3Drag = withDrag(Button3);
const Button4Drag = withDrag(Button4);
const ImagesDrag = withDrag(Images);

const App1 = () => {
  const DragLi = withDrag(() => <li>4</li>)
  return (
    <div>
      <Button1Drag></Button1Drag>
      <Button2Drag></Button2Drag>
      <Button3Drag></Button3Drag>
      <Button4Drag></Button4Drag>
      <ImagesDrag></ImagesDrag>
      <ul>
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <DragLi></DragLi>
      </ul>
    </div>
  );
};

export default App1;
